#include "grid.h"

#include "qtcpp/common.h"

Grid::Grid(Ogre::SceneManager* sceneMng, Ogre::SceneNode* parent)
{
	m_pSceneMng = sceneMng;
	m_pSceneNode = parent->createChildSceneNode();

	m_eGridType = 0;
	m_nCellSize = 1;
	m_nCellCount = 10;
	m_tGridColor = Ogre::ColourValue(0,0,0);
	m_pGridManualObj = sceneMng->createManualObject("Grid" + EasyLib::QtCpp::getUuid().toStdString());

	init();
}

Grid::~Grid()
{
	m_pSceneMng->destroyManualObject(m_pGridManualObj);

	m_pSceneMng->destroySceneNode(m_pSceneNode);
}

void Grid::init()
{
	m_pSceneNode->attachObject(m_pGridManualObj);
	update();
}

void Grid::update(PropGroup group)
{
	if (group.name != "Grid")
		return;

	if (group.data.size() != 4)
		return;

	auto types = EasyLib::QtCpp::splitStrToNum(group.data[0], ";");
	if (types.size() == 4)
	{
		m_eGridType = types[3];
	}
	m_nCellSize = group.data[1].toInt();
	m_nCellCount = group.data[2].toInt();
	auto clrs = EasyLib::QtCpp::splitStrToNum(group.data[3], ";");
	if (clrs.size() == 3)
		m_tGridColor = Ogre::ColourValue(clrs[0], clrs[1], clrs[2]);
	
	update();
}

void Grid::update()
{
	m_pGridManualObj->clear();
	m_pGridManualObj->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_LINE_LIST);
	int length = m_nCellCount * m_nCellSize;
	for (int i = 0; i < m_nCellCount + 1; i++)
	{
		m_pGridManualObj->position(-length / 2., -length / 2. + m_nCellSize * i, 0);
		m_pGridManualObj->colour(m_tGridColor);
		m_pGridManualObj->position(length / 2., -length / 2. + m_nCellSize * i, 0);
		m_pGridManualObj->colour(m_tGridColor);
	}
	for (int i = 0; i < m_nCellCount + 1; i++)
	{
		m_pGridManualObj->position(-length / 2. + m_nCellSize * i, -length / 2., 0);
		m_pGridManualObj->colour(m_tGridColor);
		m_pGridManualObj->position(-length / 2. + m_nCellSize * i, length / 2., 0);
		m_pGridManualObj->colour(m_tGridColor);
	}
	m_pGridManualObj->end();

	if (m_eGridType == 0)
		m_pSceneNode->resetOrientation();
	else if (m_eGridType == 1)
		m_pSceneNode->setOrientation(Ogre::Quaternion(Ogre::Degree(90), Ogre::Vector3::UNIT_X));
	else if (m_eGridType == 2)
		m_pSceneNode->setOrientation(Ogre::Quaternion(Ogre::Degree(90), Ogre::Vector3::UNIT_Y));
}

PropGroup Grid::getPropGroup()
{
	PropGroup group;
	group.name = "Grid";
	group.uuid = QString::fromStdString(m_pGridManualObj->getName());
	group.label = { "GridType","CellSize","CellCount","GridColor" };
	group.type = { "enum","int","int" ,"color" };
	group.data = { QString("xy;xz;yz;%1").arg(m_eGridType),
		QString::number(m_nCellSize),QString::number(m_nCellCount),
		QString("%1;%2;%3").arg(m_tGridColor.r).arg(m_tGridColor.g).arg(m_tGridColor.b)};
	group.min = { "","1","1",""};
	group.max = { "","","","" };
	group.step = { "","1","1","" };
	return group;
}

Ogre::SceneNode* Grid::getSceneNode()
{
	return m_pSceneNode;
}
